import { Instance } from "../TSUtils/Instance";

/*
 * @Author: zgl 2191723570@qq.com
 * @Date: 2023-11-25 19:12:53
 * @LastEditors: 1936 2191723570@qq.com
 * @LastEditTime: 2024-01-14 18:51:39
 * @FilePath: /client2/assets/Scripts/Core/EventManager.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
interface Event {
    cb: Function,
    ctx: any
}
export default class EventManager {

    private eventMap: Map<string | number, Event[]> = new Map();

    public static getInstance() {
        return Instance.get(EventManager);
    }

    on(eventName: string | number, cb: Function, ctx: any) {
        this.eventMap.has(eventName) ?
            this.eventMap.get(eventName).push({ cb, ctx }) :
            this.eventMap.set(eventName, [{ ctx, cb }]);
    }

    off(eventName: string | number, cb: Function, ctx: any) {
        if (!this.eventMap.has(eventName)) return;

        let events = this.eventMap.get(eventName);
        const index = events.findIndex((i) => cb === i.cb && i.ctx === ctx);
        index > -1 && events.splice(index, 1);

        if (events.length === 0) {
            this.eventMap.delete(eventName);
        }
    }

    emit(eventName: string | number, ...args: any) {
        if (!this.eventMap.has(eventName)) return;

        let events = this.eventMap.get(eventName);
        for (let i = 0; i < events.length; i++) {
            let event = events[i];
            // 使用call传入参数并且绑定this实例
            try {
                event.cb.call(event.ctx, ...args);

            } catch (error) {
                console.log(eventName + '失败')
                throw error;
            }
        }

    }

    clear() {
        this.eventMap.clear();
    }


}
